在應用程式模組的 build.gradle 檔案中使用下列依附元件
dependencies {
...
implementation("androidx.navigation:navigation-compose:2.5.2")
...
}
NavController 是負責設定狀態,並且持續追蹤組成應用程式畫面的可組合項返回堆疊,以及各個畫面的狀態。
val navController = rememberNavController()
建立NavHost時,需要使用先前透過 rememberNavController() 建立的 NavController,以及圖表起始目的地的路徑。
建立 "login" 和 "login/{content}" 兩個目的地的路徑
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyNavigationTheme {
val navController = rememberNavController()
//NavHost
NavHost(
navController = navController,
startDestination = "login"
) {
/* creating route "login" */
composable(route = "login") {
/* Using composable function */
LoginScreen(navController)
}
composable(
route = "login/{content}",
arguments = listOf(
navArgument("content") {
/* configuring arguments for navigation */
type = NavType.StringType
}
)
) {
MainScreen(
navController,
it.arguments?.getString("content")
)
}
}
}
}
}
}
換到指定頁面及使用引數進行瀏覽
navController.navigate("login/$text")
返回上一頁
navController.navigateUp() //上一頁是空的話,不會有error
@Composable
fun LoginScreen(navController: NavController) {
var text by remember {
mutableStateOf("")
}
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
OutlinedTextField(
value = text,
onValueChange = { text = it },
singleLine = true,
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = MaterialTheme.colors.onBackground,
backgroundColor = MaterialTheme.colors.background,
focusedBorderColor = MaterialTheme.colors.primary,
unfocusedBorderColor = MaterialTheme.colors.primaryVariant,
),
modifier = Modifier.border(2.dp, MaterialTheme.colors.primary)
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
/* going to main screen with the value of text */
if(!text.isNullOrEmpty()) {
// 換到指定頁面 使用引數進行瀏覽
navController.navigate("login/$text")
}
}
) {
Text(text = "帳號登入")
}
}
}
@Composable
fun MainScreen(navController: NavController, content: String?) {
require(content != null)
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(text = "歡迎\n"+content, style = MaterialTheme.typography.h1)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
/* going back to the login screen */
//返回上一頁
navController.navigateUp()
}
) {
Text(text = "登出")
}
}
}
}
@Composable
fun MainScreen(navController: NavHostController, string: String?) {
}
@Composable
fun LoginScreen(navController: NavHostController) {
}
https://betterprogramming.pub/compose-navigation-in-3-minutes-5cff3c57c34e
https://developer.android.com/jetpack/compose/navigation
Kotlin 的技術傳教士 - 范聖佑 近期也出了一本關於 Collection 的書 - Kotlin Collection 全方位解析攻略
裡面也有蠻多 operator 的介紹,歡迎大家有興趣的參考看看
https://www.tenlong.com.tw/products/9786263331136